<template>
  <div class="home">
    <el-row class="biddingHead">
      <!-- 交易预告的面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/aboutView' }">竞价公告</el-breadcrumb-item>
        <el-breadcrumb-item>竞价详情</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <!-- 竞标区域 -->
    <el-row class="biddingMiddle">
      <el-col class="biddingMiddleLeft" :span="18">
        <el-descriptions :title="bidNoticeInfo.F_PKTL_ProjectName" :column="2" size="medium" :labelStyle="{ 'font-weight': 'bold' }">
          <el-descriptions-item label="项目编号" :span=2>{{bidNoticeInfo.BillNo}}</el-descriptions-item>
          <el-descriptions-item label="竞拍开始时间 ">{{
            getdateFormat(bidNoticeInfo.F_PKTL_BeginDatetime, 'yyyy-MM-dd HH:mm')
          }}</el-descriptions-item>
          <el-descriptions-item label="竞拍结束时间 ">{{
            getdateFormat(bidNoticeInfo.F_PKTL_EndDatetime, 'yyyy-MM-dd HH:mm')
          }}</el-descriptions-item>
        </el-descriptions>
        <el-divider></el-divider>
        <el-descriptions title="" :column="2" size="medium" :labelStyle="{ 'font-weight': 'bold' }">
          <el-descriptions-item label="品名 ">{{ bidNoticeInfo.F_PKTL_MaterialName }}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions title=" " :column="4">
          <el-descriptions-item label="竞价模式 ">{{
            getBusinessInfoValue(bidNoticeInfo.F_PKTL_BiddingMode, 'F_PKTL_BiddingMode')
          }}</el-descriptions-item>
          <el-descriptions-item label="是否需要保证金 ">{{
            getBusinessInfoValue(bidNoticeInfo.F_PKTL_IsNeedPledge, 'F_PKTL_IsNeedPledge')
          }}</el-descriptions-item>
          <el-descriptions-item label="延迟时间 ">{{ bidNoticeInfo.F_PKTL_DelayMinutes }} 分钟</el-descriptions-item>
          <el-descriptions-item label="物料类型 ">{{
            getBusinessInfoValue(bidNoticeInfo.F_PKTL_MaterialType, 'F_PKTL_MaterialType')
          }}</el-descriptions-item>
          <el-descriptions-item label="保留价 ">{{
            getBusinessInfoValue(bidNoticeInfo.F_PKTL_IsRetained, 'F_PKTL_IsRetained')
          }}</el-descriptions-item>
          <el-descriptions-item label="涨幅值 ">{{bidNoticeInfo.F_PKTL_Increment}}</el-descriptions-item>
          <el-descriptions-item label="看货时间" :span="2">{{
            getdateFormat(bidNoticeInfo.F_PKTL_CheckDate, 'yyyy-MM-dd')
          }}</el-descriptions-item>
          <el-descriptions-item label="看货地点 ":span="2">{{bidNoticeInfo.F_PKTL_CheckAddress}}</el-descriptions-item>
          <el-descriptions-item label="备注 ">
            {{
              bidNoticeInfo.F_PKTL_Remarks !== null || bidNoticeInfo.F_PKTL_Remarks !== '' || bidNoticeInfo.F_PKTL_Remarks !== ' '
                ? bidNoticeInfo.F_PKTL_Remarks
                : '暂无'
            }}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <!-- 竞标操作框 -->
      <el-col class="biddingMiddleright" :span="6" v-if="this.bidStatus == 2" >
        <div class="biddingMiddlerightDiv">
          <div class="bidTitle">竞标结束倒计时</div>
          <div class="bidStatistic">
            <el-statistic  @finish="bidFinish" :value="bidStopTime" time-indices format="HH:mm:ss"></el-statistic>
          </div>
          <div class="currentPrice">当前价格：{{ bidNoticeInfo.F_PKTL_CurrentAmount }}</div>
          <el-input-number v-if="this.isEnrolled==true && this.isNeedPledged==true" :step="bidNoticeInfo.F_PKTL_Increment" v-model="biddingInput" ></el-input-number>
          <div style="color=red">{{ biddingWarningMessage }}</div><br />
          <el-button v-if="this.isEnrolled==true && this.isNeedPledged==true" type="primary" @click="biddingButton">出价</el-button>

        </div>
      </el-col>
      <el-col class="biddingMiddleright" :span="6" v-if="this.bidStatus == 3" >
        <div class="biddingMiddlerightDiv">
          <div class="bidTitle">竞标结束倒计时</div>
          <div class="currentPrice">成交价格：{{ bidNoticeInfo.F_PKTL_CurrentAmount }}</div>
          <div class="tl-icon-yijieshu"></div>
        </div>
      </el-col>
      <el-col class="biddingMiddleright" :span="6" v-if="this.bidStatus == 1" >
        <div class="biddingMiddlerightDiv">
          <div class="bidTitle">竞标开始倒计时</div>
          <div class="bidStatistic">
            <el-statistic  @finish="bidStart" :value="bidStartTime" time-indices format="HH:mm:ss"></el-statistic>
          </div>
          <div class="currentPrice">起拍价格：{{ bidNoticeInfo.F_PKTL_CurrentAmount }}</div>
          <div class="tl-icon-daikaishi"  v-if="this.isEnrolled==true && this.isNeedPledged==true"></div>
          <el-button v-if="this.isEnrolled==true && this.isNeedPledged==false" type="danger" >待交保证金</el-button>
          <el-button v-if="this.isEnrolled==false" type="danger" @click="enrollInButton">报名参加</el-button>
        </div>
      </el-col>


    </el-row>
    <!-- 附件区域 -->
    <el-row class="biddingAccessory">
      <el-col :span="24">
        <el-tabs type="border-card">
          <el-tab-pane label="竞价公告">
            <!-- 场次信息的内容 -->
            <el-descriptions title="场次信息" :column="4" size="medium" border>
              <el-descriptions-item>
                <template slot="label"> 物料类型 </template>
                {{ getBusinessInfoValue(bidNoticeInfo.F_PKTL_MaterialType, 'F_PKTL_MaterialType') }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 竞价模式 </template>
                {{ getBusinessInfoValue(bidNoticeInfo.F_PKTL_BiddingMode, 'F_PKTL_BiddingMode') }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 是否需要保证金 </template>
                {{ getBusinessInfoValue(bidNoticeInfo.F_PKTL_IsNeedPledge, 'F_PKTL_IsNeedPledge') }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 保证金 </template>
                {{ bidNoticeInfo.F_PKTL_PledgeAmount }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 竞拍开始时间 </template>
                {{ getdateFormat(bidNoticeInfo.F_PKTL_BeginDatetime, 'yyyy-MM-dd HH:mm') }} </el-descriptions-item
              ><el-descriptions-item>
                <template slot="label"> 竞拍结束时间 </template>
                {{ getdateFormat(bidNoticeInfo.F_PKTL_EndDatetime, 'yyyy-MM-dd HH:mm') }} </el-descriptions-item
              ><el-descriptions-item>
                <template slot="label"> 延时分钟 </template>
                {{ bidNoticeInfo.F_PKTL_DelayMinutes }} 分钟 </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 起拍价 </template>
                {{ bidNoticeInfo.F_PKTL_BeginAmount }}
              </el-descriptions-item>
            </el-descriptions>
            <br />
            <!--  -->
            <el-descriptions title="物料信息" :column="1" size="size" border>
              <el-descriptions-item :contentStyle="{ width: '85%' }">
                <template slot="label"> 商品名称 </template>
                {{ bidNoticeInfo.F_PKTL_MaterialName }}
              </el-descriptions-item> </el-descriptions
            ><br />
            <el-descriptions title="" :column="4" size="size" border>
              <el-descriptions-item :labelStyle="{ width: '10%' }">
                <template slot="label"> 材质 </template>
                {{ bidNoticeInfo.F_PKTL_GoodMaterial }}
              </el-descriptions-item>
              <el-descriptions-item :labelStyle="{ width: '10%' }">
                <template slot="label"> 规格 </template>
                {{ bidNoticeInfo.F_PKTL_MaterialSpec }}
              </el-descriptions-item>
              <el-descriptions-item :labelStyle="{ width: '10%' }">
                <template slot="label"> 预估数量 </template>
                {{ bidNoticeInfo.F_PKTL_ForecastQty }}
              </el-descriptions-item>
              <el-descriptions-item :labelStyle="{ width: '10%' }">
                <template slot="label"> 预估数量 </template>
                {{ bidNoticeInfo.F_PKTL_ForecastQty }}
              </el-descriptions-item>
            </el-descriptions>
            <el-descriptions title="" :column="1" size="size" border>
              <el-descriptions-item :contentStyle="{ width: '85%' }">
                <template slot="label"> 备注 </template>
                {{ bidNoticeInfo.F_PKTL_Remarks }}
              </el-descriptions-item>
            </el-descriptions>
            <!-- 图片描述 -->
            <el-descriptions title="图文说明" :column="1" size="size" border>
            </el-descriptions>
              <div v-html="bidNoticeInfo.F_PKTL_ImageDescription"></div>
            
          </el-tab-pane>
          <el-tab-pane label="竞价服务协议">
            <div v-html="bidNoticeInfo.F_PKTL_ServiceAgreement"></div>
          </el-tab-pane>
          <el-tab-pane label="交易规则">
            <div v-html="bidNoticeInfo.F_PKTL_TradeRules"></div>
          </el-tab-pane>
          <el-tab-pane label="附件">
            <div v-html="bidNoticeInfo.F_PKTL_ImageDescription"></div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { connectWebsocket, websocketSendInfo,closeWebsocket } from '../common/Socket.js'
import { Base64 } from 'js-base64'
import tenderOpetion from '../echarts/tenderEcharts.js'

import { ref } from 'vue'
export default {
  data() {
    return {
      bidStep:"10",
      bidStartTime:Date.now(),
      // 倒计时的时间
      bidStopTime: Date.now() + 1000 * 60 * 60 * 8,
      // 获取首页传来的竞标id
      billNo: '',
      // 通过金蝶接口查看的数据
      bidNoticeInfo: {},
      // 元数据的信息
      businessInfo: {},
      // 价格和测试数据
      waresPrice:0,
      //接收消息内容
      receiveMsgInfo:{},
      wsParams: {},
      // 金蝶查询参数
      params: {},
      // 出价框设置
      biddingInput: '',
      // 出价的提示信息
      dialogFormVisible: false,
      // 出价的警告信息
      biddingWarningMessage: '',
      //currentUserId
      currentUserId:'',
      //是否报名
      isEnrolled:false,
      //项目状态
      bidStatus:'',
      //保证金状态，默认false不需要
      isNeedPledged:false,

      opetion:tenderOpetion.opetion,
    }
  },
  inject:[
  'reload'
  ],
  beforeCreate(){
  },
  watch:{
  // 被监听的属性
   
    receiveMsgInfo:{
      handler(newVal,olderVal){
        this.refreshBidAuction(newVal)
      }
    }
  },
  // created周期可以访问到data数据和methods的方法
  created() {
    // 路由跳转
    this.billNo = this.$route.query.billNo
    this.currentUserId=sessionStorage.getItem("userId")
    this.wsParams={id:'0',dataType:'connection',msg:'连接'}

    let wsHeaderData=[]
    wsHeaderData.push(this.billNo)
    if(this.currentUserId!=null){
      wsHeaderData.push(this.currentUserId)
    }
    else{
      wsHeaderData.push('未登录')
    }
     // 创建webSocket
    connectWebsocket(wsHeaderData,this.wsParams,(data) => {
        console.log('成功的回调函数, 接收到的data数据： ', data)
        this.SocketMessage(data)
      },
      () => {
        console.log('失败的回调函数')
        
      }
    )
    // 调用初始化金蝶查询需要的参数
    this.buildParams()
    // 调用元数据的的方法
    this.loadBusinessInfo()
  },
  // 挂载之后
  mounted() {
    this.currentUserId=sessionStorage.getItem("userId")
    document.addEventListener('visibilitychange', this.handleVisiable)  
    // 获取竞标的页面
    this.loadBiddingNotice(this.params)
  },
  // 组件销毁前
  beforeDestroy(){
    document.removeEventListener('visibilitychange', this.handleVisiable) 
    closeWebsocket()
    console.log("竞标页面销毁")
  },
  // 方法区
  methods: {
    // 金蝶初始化需要的参数
    buildParams() {
      this.currentUserId=sessionStorage.getItem("userId")
      this.params = { FormId: '', data: { Number: '' } }
      this.params.FormId = 'PKTL_BiddingNotice'
      this.params.data.Number = this.billNo
    },
    // 金蝶元数据查询方法
    loadBusinessInfo() {
      this.$api.billBusinessInfo.queryBusinessInfo('PKTL_BiddingNotice').then((res) => {
        this.businessInfo = res
        console.log('元数据是：', res)
      })
    },
    // 金蝶请求获取查看的数据
    loadBiddingNotice(params) {
      const data = JSON.parse(JSON.stringify(params))
      this.$api.biddingNotice.billView(data).then((res) => {
        if (res.Result.ResponseStatus.IsSuccess) {

          this.bidNoticeInfo = res.Result.Result
          this.wsParams['id']=this.bidNoticeInfo.Id
          this.biddingInput=this.bidNoticeInfo.F_PKTL_CurrentAmount 

          // 项目状态（未开始、进行中、已结束）
          this.bidStatus=this.bidNoticeInfo.F_PKTL_BidStatus
          this.bidStep=this.bidNoticeInfo.F_PKTL_Increment

          // 重置对象的竞价服务协议
          this.bidNoticeInfo.F_PKTL_ServiceAgreement =
            res.Result.Result.F_PKTL_ServiceAgreement === null ? null : Base64.decode(res.Result.Result.F_PKTL_ServiceAgreement)
          // 重置对象的交易规则
          this.bidNoticeInfo.F_PKTL_TradeRules =
            res.Result.Result.F_PKTL_TradeRules === null ? null : Base64.decode(res.Result.Result.F_PKTL_TradeRules)
          // 图片详情
          this.bidNoticeInfo.F_PKTL_ImageDescription =
            res.Result.Result.F_PKTL_ImageDescription === null ? null : Base64.decode(res.Result.Result.F_PKTL_ImageDescription)
          this.bidStartTime=Date.now() + (Date.parse(res.Result.Result.F_PKTL_BeginDatetime) - Date.now())
          // 重置对象的时间
          this.bidStopTime = Date.now() + (Date.parse(res.Result.Result.F_PKTL_EndDatetime) - Date.now())
          // this.bidStopTime = Date.now() + 1000 *  60 *1
          var t_BidNoticeCustomer=res.Result.Result.PKTL_t_BidNoticeCustomer

          this.isEnrolled=false;
          t_BidNoticeCustomer.forEach(bidCustomer => {
            if(bidCustomer.F_PKTL_BidCustomerId_Id==this.currentUserId){
              this.isEnrolled=true

              //判断是否需要交保证金【F_PKTL_IsNeedPledge==1)】
              //不需要交保证金直接this.isNeedPledged=true
              //需要在判断是不是已经交了保证金【bidCustomer.F_PKTL_PledgelStatus==1】
              //
              if(this.bidNoticeInfo.F_PKTL_IsNeedPledge==1){
                  if(bidCustomer.F_PKTL_PledgelStatus==1){
                    this.isNeedPledged=true
                  }
                  else{
                    this.isNeedPledged=false
                  }
              }
              else{
                this.isNeedPledged=true
              }
            }
          });

        }
      })
    },
    // 接收消息的方法
    SocketMessage(data) {
      console.log('结束消息的方法走不走')
        this.receiveMsgInfo=JSON.parse(data)
        this.refreshBidAuction(this.receiveMsgInfo)
        
    },
    // 点击向服务器发送消息
    send() {
      // this.waresPrice=ref(string)
      var that=this
      websocketSendInfo(JSON.stringify(this.wsParams), (data) => {
        console.log('点击后成功的回调函数, 接收到的data数据： ', data)
        this.receiveMsgInfo=JSON.parse(data)

        // if(this.receiveMsgInfo.code=='1'){
        //   if(this.receiveMsgInfo.dataType=='price'){
        //     this.$message({
        //       message: '出价成功！',
        //       type: 'success',
        //       center: true,
        //     })
        //     this.bidNoticeInfo.F_PKTL_CurrentAmount=this.receiveMsgInfo.msg
        //     this.waresPrice = this.receiveMsgInfo.msg
        //   }
        // }
      })
    },
    // 点击出价按钮触发的方法，验证出价合法性，连接金蝶后台修改出价数据库
    biddingButton() {

      // 判断出价合法性
      if (this.biddingInput === null || this.biddingInput === '' || this.biddingInput === 0) {
        this.$message.error({
          message: '出价失败：请输入正确的价格格式',
          center: true,
        })
      } else if (this.biddingInput <= this.bidNoticeInfo.F_PKTL_CurrentAmount) {
        //防止输入多个小数点
        this.$message({
          message: '出价失败：出价不能低于当前价格',
          type: 'warning',
          center: true,
        })
      } else {
        this.wsParams['msg']=this.biddingInput
        this.wsParams['dataType']='bid'
        this.send()
        
      }
    },

    //报名
    enrollInButton(){
      if(this.currentUserId===null){
        alert('请先登录')
        return
      }
      else{
        let data=[{
                "FId":this.bidNoticeInfo.Id,
                "CustomerId":this.currentUserId,
                "BillNo":this.billNo
                }]
        this.$api.biddingNotice.enrollIn(data).then((res) => {

          if(res.isSuccess=='true'){
            this.isEnrolled=true;
            //如果需要保证金，判断客户保证金交款状态。
            if(this.bidNoticeInfo.F_PKTL_IsNeedPledge==1){
              if(bidCustomer.F_PKTL_PledgelStatus==1){
                this.isNeedPledged=true
              }
              else{
                this.isNeedPledged=false
              }
            }
            else{
              this.isNeedPledged=true
            }
          }
          else{
             this.$message({
                message: res.msg,
                type: 'error',
                center: true,
              })
          }
        })
      }
    },


    //开始项目
    bidStart(){
      this.bidStatus=2
    },
    //结束项目
    bidFinish(){
      let data=[{
                "FId":this.bidNoticeInfo.Id,
                }]
      this.$api.biddingNotice.bidEndAuction(data).then(res=>{
        if(res.isSuccess=='true'){
          this.bidStatus=3
        }
      })
    },
    refreshBidAuction(data){
        if(data.dataType=='price'){
          if(data.code=='1'){
            this.bidNoticeInfo.F_PKTL_CurrentAmount=data.msg
            this.bidStopTime = Date.parse(data.endDateTime)
          }
          else{
            // this.bidStopTime = Date.parse(data.currentDateTime) + (Date.parse(data.endDateTime) - Date.parse(data.currentDateTime))
            this.bidStopTime = Date.parse(data.endDateTime)
            this.$message({
                message: data.msg,
                type: 'error',
                center: true,
              })
          }
        }
        if(data.dataType=='noStart'){
            this.bidStartTime=Date.parse(data.endDateTime)
            this.bidStatus=1
        }
        if(data.dataType=='server'){
          if(data.msg==this.billNo){
            this.bidStatus=3
          }
        }
    },
    handleVisiable(e){
      if (document.visibilityState == "visible"){
        this.reload()
      }
    },
    getBusinessInfoValue(fieldValue, fieldKey) {
      if (this.businessInfo != {}) {
        return this.Common.getFieldValue(fieldValue, fieldKey, this.businessInfo)
      }
    },
    getdateFormat(dataValue, format) {
      return this.Common.dateFormat(dataValue, format)
    },

    //仪表盘代码，未使用，如需使用需要再对应时点调用该方法
    initCharts(e){
      var chartDom = document.getElementById('auctionEcharts');
      var myChart = this.$echarts.init(chartDom,null, {
          width: 400,
          height: 400
        });
      console.log("tenderOpetion.opetion")
      console.log(tenderOpetion.opetion)
      myChart.setOption(tenderOpetion.option, true); 

      const dataEchartsValue=(Math.random() * 100)
      if(e==true){
        dataEchartsValue=0
      }
      myChart.setOption({
                series: [{ data: [{ value: +(dataEchartsValue).toFixed(2)}] }]
              })
    }
  },
}
</script>

<style scoped>
#auctionEcharts{

}

body {
  padding: 0px;
  margin: 0px;
}
.home {
  width: 80%;
  margin: auto;
}
.el-breadcrumb {
  margin-left: 20px;
  line-height: 40px;
}
.el-tabs {
  width: 100%;
}
/* 面包屑 */
.biddingHead .el-breadcrumb {
  font-size: 10px;
}
/* 竞标中部 */
.biddingMiddle {
  widows: 1299px;
  border: 1px solid rgba(171, 248, 255, 0.692);
  background-color: rgba(255, 255, 255, 0.945);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.biddingMiddle .el-descriptions {
  margin: 10px 20px;
}
.biddingMiddleright {
  width: 25%;
  background-color: rgba(219, 239, 255, 0.383);
  height: 360px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  padding: 20px 20px;
}
.bidTitle{
  color:blue;
  font-size:30px;
  font-weight: bold;
  margin-bottom: 15px;
}
.bidStatistic>>> .number{
  font-size:30px;
  font-weight:bold;
}
.currentPrice{
  font-size:25px;
  font-weight: bold;
  margin-top: 15px;
  margin-bottom: 15px;
}
.tl-icon-yijieshu,.tl-icon-daikaishi{
  font-size:100px;
  color: red;
}
/* .biddingMiddlerightDiv{
  width: 30%;
} */
.biddingMiddlerightDiv span {
  font-size: 20px;
  line-height: 60px;
}
/* 竞标附件 */
.biddingAccessory {
  margin-top: 5px;
}
.biddingAccessory .el-tab-pane {
  height: 666px;
  overflow-x: hidden;
  overflow-y: auto;
  text-align: left;
}
</style>